/*
 * This js file for conference.jsp only
 */
var layout;
var txtColorPicker,bgColorPicker;
var participantGrid;

$(function(){
	$('.easyui-validatebox').validatebox();
	$('.easyui-validatebox[required]').after("<font color='red'> *</font>");
	/*
	$('#id_endTime').datetimepicker({
		dateFormat: 'yy-mm-dd',
		showButtonPanel:false
	});
	*/
	var myCalendar = new dhtmlXCalendarObject(["id_endTime"]);
	myCalendar.setDateFormat("%Y-%m-%d %H:%i:%s");
	
	loadGroup();
	initProfile();
	initParticipant();
	
	layout=new dhtmlXLayoutObject("id_win_container","2U");
	layout.forEachItem(function(item){
		item.hideHeader();
	});
	layout.cells("a").setWidth(200);
	layout.cells("a").fixSize(true,true);
	layout.cells("a").attachObject("id_list");
	
	layout.cells("b").attachObject("id_container_right");
	
	layout.attachFooter("id_footer");
	
	showItem("id_general");
	
	// 高亮左侧的菜单选项
	$(".menu-item").click(function(){
	    $(".menu-item").css("font-weight","normal");
	    $(this).css("font-weight","bold");
	});
	
	//---------------initialize color picker------------
	txtColorPicker=new dhtmlXColorPicker("id_txt_cp",false,false,true);
	txtColorPicker.loadUserLanguage("my-lang");
	txtColorPicker.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
	txtColorPicker.init();
	txtColorPicker.setOnSelectHandler(function(c){
		$("#id_textColor").val(c);
		$("#id_textColor").css("background-color",c);
	});
	$("#id_textColor").click(function(){
		txtColorPicker.show();
	});
	
	bgColorPicker=new dhtmlXColorPicker("id_bg_cp",false,false,true);
	bgColorPicker.loadUserLanguage("my-lang");
	bgColorPicker.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
	bgColorPicker.init();
	bgColorPicker.setOnSelectHandler(function(c){
		$("#id_textBgColor").val(c);
		$("#id_textBgColor").css("background-color",c);
	});
	$("#id_textBgColor").click(function(){
		bgColorPicker.show();
	});
	
	var opt="${param.opt}";// page state "new" or "modify"
	
	if(opt=="new"){// init new page values
		$("select[name=bandwidth]").val("1024");
		$("input[name=callInType][value=all]").attr("checked",true);
		$("input[name=encrypt][value=disable]").attr("checked",true);
		$("input[name=h263cif4Enabled]").attr("checked",true);
		$("input[name=h264Enabled]").attr("checked",true);
        if("${sessionScope.loginInfo.h264definition}"=='CIF')
            $("select[name=h264Definition]").val("CIF");
        else if("${sessionScope.loginInfo.h264definition}"=='CIF4')
            $("select[name=h264Definition]").val("CIF4");
        else
             $("select[name=h264Definition]").val("HD720P");
		$("input[name=h239Enabled]").attr("checked",true);
		$("select[name=h239Bandwidth]").val("128");
		$("select[name=h239Codec]").val("H.263");
		
		$("input[name=audioFormatsArray]").each(function(){
			this.checked=true;
		});
		
		$("select[name=textPosition]").val("bottom_center");
		$("select[name=textFont]").val("middle");
		
		$("select[name=broadcastBandwidth]").val("384");
	}else if(opt=="modify"){// init modify page values
		if("${model.endLimit}"=="true"){
			$("input[name=endLimit]").attr("checked",true);
		}
		$("select[name=bandwidth]").val("${model.bandwidth}");
		$("input[name=callInType][value=${model.callInType}]").attr("checked",true);
		$("input[name=encrypt][value=${model.encrypt}]").attr("checked",true);

		if("${model.muteOnJoin}"=="true"){
			$("input[name=muteOnJoin]").attr("checked",true);
		}
		
		if("${model.h263cif4Enabled}"=="true"){
			$("input[name=h263cif4Enabled]").attr("checked",true);
		}
		if("${model.h264Enabled}"=="true"){
			$("input[name=h264Enabled]").attr("checked",true);
		}
		$("select[name=h264Definition]").val("${model.h264Definition}");
		if("${model.h239Enabled}"=="true"){
			$("input[name=h239Enabled]").attr("checked",true);
		}
		$("select[name=h239Bandwidth]").val("${model.h239Bandwidth}");
		$("select[name=h239Codec]").val("${model.h239Codec}");
		
		$("input[name=audioFormatsArray]").each(function(){
			if(",${model.audioFormats},".indexOf(","+this.value+",")!=-1){
				this.checked=true;
			}
		});
		
		$("select[name=textPosition]").val("${model.textPosition}");
		$("select[name=textFont]").val("${model.textFont}");
		
		$("#id_textColor").val("${model.textColor}");
		$("#id_textColor").css("background-color","${model.textColor}");
		$("#id_textBgColor").val("${model.textBgColor}");
		$("#id_textBgColor").css("background-color","${model.textBgColor}");
		
		if("${model.textBgEnabled}"=="true"){
			$("input[name=textBgEnabled]").attr("checked",true);
		}
		if("${model.broadcastEnabled}"=="true"){
			$("input[name=broadcastEnabled]").attr("checked",true);
		}
		$("select[name=broadcastBandwidth]").val("${model.broadcastBandwidth}");
		
		json2participantGrid('${model.participantsJSON}');
	}
	
});

function doSubmit(){
	participantGrid2JSON();
	
	$('#id_form').form('submit', {
        url:"<c:url value='/app/manage/conf'/>",
        onSubmit: function(){
        	if($('.easyui-validatebox').validatebox("isValid")==false){
        		return false;
        	}else if(isExist()){
        		alert(messages.getMsg("error.exist",[$("#id_number").val()]));
        		return false;
        	}else{
				return true;
			}
        },
        success:function(data){
			//alert(data);
			parent.onlineConfObj.reload();
			parent.closeWin();
        }
	});
}

function isExist(){
	var ret=false;
	var _key=$("#id_number").val();
	var _preKey="<c:out value='${model.number}'/>";
	
	if("${param.opt}"=="modify"&&_key==_preKey){//whether is the same key in the modify page
		ret=false;
	}else{
		$.ajax({
			url:"<c:url value='/app/manage/conf/check'/>",
			async:false,
			type:"GET",
			data:{
				key:$("#id_number").val(),
				times:new Date().toString()
			},
			success:function(data){
				if(data=="true")
					ret=true;
			}
		});
	}
	
	return ret;
}

//initialize "id_profile" select options
function initProfile(){
	$.ajax({
		url:"<c:url value='/app/manage/profile/combox'/>",
		type:"GET",
		data:{
			times:new Date().toString()
		},
		success:function(data){
			var profiles=$.parseJSON(data);
			
			$.each(profiles,function(){
				$("#id_profile").append("<option value='"+this+"'>"+this+"</option>");
			});
			//bind change event,put relative values from profile to this page when change event occurred
			$("#id_profile").change(function(){
				var profileName=this.value;
				if(profileName=="") return;
				if(!confirm(messages.getMsg('confirm.useProfile'))) return;
				
				$.ajax({
					url:"<c:url value='/app/manage/profile/json'/>",
					type:"GET",
					async:false,
					data:{
						name:profileName,
						times:new Date().toString()
					},
					success:function(retData){
						var pObj=$.parseJSON(retData);
						//copy pObj values to relative elements
						$("input[name='name']").val(pObj['confName']);
						$("select[name='bandwidth']").val(pObj['bandwidth']);
						$("input[name='maxAudioPorts']").val(pObj['maxAudioPorts']);
						$("input[name='maxVideoPorts']").val(pObj['maxVideoPorts']);
						if(pObj['reservedAudioPorts']=="true"){
							$("input[name='reservedAudioPorts']").attr("checked",true);
						}else{
							$("input[name='reservedAudioPorts']").attr("checked",false);
						}
						if(pObj['reservedVideoPorts']=="true"){
							$("input[name='reservedVideoPorts']").attr("checked",true);
						}else{
							$("input[name='reservedVideoPorts']").attr("checked",false);
						}
						$("input[name='encrypt'][value='"+pObj['encrypt']+"']").attr("checked",true);
						$("input[name='callInType'][value='"+pObj['callInType']+"']").attr("checked",true);
						if(pObj['muteOnJoin']=="true"){
							$("input[name='muteOnJoin']").attr("checked",true);
						}else{
							$("input[name='muteOnJoin']").attr("checked",false);
						}
						var formats=pObj["audioFormats"].split(',');
						//clean checked
						$("input[name='audioFormatsArray']").attr("checked",false);
						$.each(formats,function(){
							$("input[name='audioFormatsArray'][value='"+this+"']").attr("checked",true);
						});
						if(pObj['h263cif4Enabled']=="true"){
							$("input[name=h263cif4Enabled]").attr("checked",true);
						}else{
							$("input[name=h263cif4Enabled]").attr("checked",false);
						}
						$("select[name=h264Definition]").val(pObj['h264Definition']);
						$("select[name=h239Bandwidth]").val(pObj['h239Bandwidth']);
						if(pObj['h239Enabled']=='true'){
							$("input[name=h239Enabled]").attr("checked",true);
						}else{
							$("input[name=h239Enabled]").attr("checked",false);
						}
						$("select[name=h239Codec]").val(pObj['h239Codec']);
						$("select[name=textPosition]").val(pObj['textPosition']);
						$("select[name=textFont]").val(pObj['textFont']);
						$("input[name=textColor]").val(pObj['textColor']);
                        $('input[name=textBgColor]').val(pObj['textBgColor']);
						if(pObj['textBgEnabled']=='true'){
							$("input[name=textBgEnabled]").attr("checked",true);
						}else{
							$("input[name=textBgEnabled]").attr("checked",false);
						}
                        $('input[name=textDisplayTime]').val(pObj['textDisplayTime']);
						
						if(pObj['broadcastEnabled']=='true'){
							$("input[name=broadcastEnabled]").attr("checked",true);
						}else{
							$("input[name=broadcastEnabled]").attr("checked",false);
						}
						$('select[name=broadcastBandwidth]').val(pObj['broadcastBandwidth']);
						$('input[name=broadcastNumLimit]').val(pObj['broadcastNumLimit']);
						$('input[name=broadcastPassword]').val(pObj['broadcastPassword']);
						$('textarea[name=topic]').val(pObj['description']);
					}
				});
			});
		}
	});
}

function loadGroup(){
	$.ajax({
		url:"<c:url value='/app/manage/group/combox'/>",
		type:"GET",
		data:{
			times:new Date().valueOf()
		},
		success:function(data){
			var groups=eval(data);
			$.each(groups,function(){
				$("#id_group").append("<option value='"+this.name+"'>"+this.name+"</option>");
			});
			
			setTimeout(function(){
				$("#id_group").val("${model.group}");
			},100);
		}
	});
}

function showItem(id){
	var items=["id_general","id_auv","id_osd","id_broadcast","id_participant"];
	$.each(items,function(){
		if(this==id){
			document.getElementById(this).style.display="block";
		}else{
			document.getElementById(this).style.display="none";
		}
	});
}

function closeAddressPopWin(){
	if(layout.dhxWins.isWindow("id_win_addressbook")){
		layout.dhxWins.window("id_win_addressbook").close();
	}
}
//initialize participant tab panel
function initParticipant(){
	var toolbar=new dhtmlXToolbarObject("id_participant_bar");
	toolbar.addButton("id_participant_btn_addressbook",1,"<fmt:message key='toolbar.conf.participant.addressbook'/>","<c:url value='/styles/default/images/addressbook16.png'/>");
	toolbar.addButton("id_participant_btn_delete",2,"<fmt:message key='toolbar.conf.participant.delete'/>","<c:url value='/styles/default/images/delete16.png'/>");
	
	toolbar.attachEvent("onClick",function(id){
		if(id=="id_participant_btn_addressbook"){
			var popwin=layout.dhxWins.createWindow("id_win_addressbook",0,0,600,480);
			//layout.dhxWins.setImagePath("<c:url value='/styles/dhx2/imgs/' />");
			popwin.denyResize();
			popwin.setModal(true);
			popwin.center();
			popwin.button("minmax1").hide();
			popwin.button("minmax2").hide();
			popwin.setText("<fmt:message key='panel.title.addressBook'/>");
			popwin.attachURL("<c:url value='/app/manage/addressbook/win'/>?parent=conf");
			popwin.setIcon("addressbook16.png");
		}
		if(id=="id_participant_btn_delete"){
			var rowIds=participantGrid.getSelectedRowId();
			if(rowIds==null){
				alert(messages.getMsg("noSelect.tip"));
			}else{
				$.each(rowIds.split(","),function(){
					participantGrid.deleteRow(this);
				});
			}
		}
	});
	
	participantGrid=new dhtmlXGridObject("id_participant_grid");
	participantGrid.setImagePath("<c:url value='/styles/dhx2/imgs/'/>");
	participantGrid.setHeader([
	   						"<fmt:message key='grid.conf.participant.number'/>",
	   						"<fmt:message key='grid.conf.participant.displayName'/>",
	   						"<fmt:message key='grid.conf.participant.invite'/>",
	   						"<fmt:message key='grid.conf.participant.IP'/>",
	   						"<fmt:message key='grid.conf.participant.video'/>",
	   						"<fmt:message key='grid.conf.participant.bandwidth'/>",
	   						"email",
	   						"name"
	   		                ],null,[
	   		                        "text-align:center",
	   		                        "text-align:center",
	   		                        "text-align:center",
	   		                        "text-align:center",
	   		                        "text-align:center",
	   		                        "text-align:center",
	   		                     	"text-align:center",
	   		                     	"text-align:center"
	   		                     ]);
	participantGrid.setInitWidths("*,*,*,*,*,*,0,0");
   	participantGrid.setColTypes("ro,ed,ch,ro,ch,coro,ro,ro");
   	participantGrid.setColumnColor("white,yellow,white,white,white,yellow,white,white");
   	participantGrid.enableMultiselect(true);
   	var combo=participantGrid.getCombo(5);
   	$.each([128,192,256,320,384,448,512,640,768,1024,1536,1920,2048,2560,3072,3584,4096],function(){
   		combo.put(this,this);
   	});
   	participantGrid.setSkin("${skin}");
   	participantGrid.init();
}

//convert participant grid rows value to json string and set the value to "participantsJSON" hidden input
function participantGrid2JSON(){
	var participants=[];
	participantGrid.forEachRow(function(id){
		var p={
			p_number:participantGrid.cells(id,0).getValue(),
			p_nameOverrideValue:participantGrid.cells(id,1).getValue(),
			p_autoInvite:participantGrid.cells(id,2).getValue()=="1"?"true":"false",
			p_ip:participantGrid.cells(id,3).getValue(),
			p_videoEnabled:participantGrid.cells(id,4).getValue()=="1"?"true":"false",
			p_bandwidth:participantGrid.cells(id,5).getValue(),
			p_email:participantGrid.cells(id,6).getValue(),
			p_name:participantGrid.cells(id,7).getValue()
		};
		participants.push(p);
	});
	
	//alert($.toJSON(participants));
	$("input[name=participantsJSON]").val($.toJSON(participants));
}

//convert participants json string to participants grid row in modify state
function json2participantGrid(json){
	var pArray=$.parseJSON(json);
	if(pArray){
		$.each(pArray,function(){
			var rowId=this.p_number;
			var row=[
						this.p_number,
						this.p_nameOverrideValue,
						this.p_autoInvite=="true"?"1":"0",
			         	this.p_ip,
			         	this.p_videoEnabled=="true"?"1":"0",
			         	this.p_bandwidth
			           ];
			participantGrid.addRow(rowId,row);
			//participantGrid.setCellTextStyle(rowId,1,"border:1px solid gray;");
			//participantGrid.setCellTextStyle(rowId,5,"border:1px solid gray;");
		});
	}
}
